<template>
    <div>
        <!-- 三级分类全局组件 -->
        <Category :scene="scene"></Category>
        <!--展示某一个三级分类下的平台属性与属性值-->
        <el-card shadow="always" style="margin-top: 10px">
            <div v-show="scene == 0">
                <el-button type="primary" size="default" :icon="Plus" style="margin-bottom: 10px" @click="addAttr"
                    :disabled="!categoryStore.c3Id">添加属性</el-button>
                <el-table border stripe :data="attrList">
                    <el-table-column label="序号" width="80" type="index" align="center">
                    </el-table-column>
                    <el-table-column label="属性名称" width="120" prop="attrName" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <el-tag style="margin: 0px 3px" class="ml-2"
                                :type="attrVal.id % 2 == '0' ? 'success' : 'warning'"
                                v-for="(attrVal, index) in row.attrValueList" :key="attrVal.id">{{ attrVal.valueName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #="{ row, $index }">
                            <el-button type="primary" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
                            <el-button type="danger" size="small" :icon="Delete"  @click="removeAttr(row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="scene == 1">
                <!-- 添加属性|修改属性的结构 -->
                <el-form ref="form" :inline="true">
                    <el-form-item label="属性名">
                        <!-- 收集属性名字 -->
                        <el-input placeholder="请你输入属性的名字" size="normal" clearable v-model="attrParams.attrName">
                        </el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" :icon="Plus" :disabled="!attrParams.attrName" @click="addAttrValue">添加属性值
                </el-button>
                <el-button @click="cancel">取消</el-button>
                <!-- 将来表格展示属性值的地方 -->
                <el-table border stripe style="margin: 10px 0px" :data="attrParams.attrValueList">
                    <el-table-column type="index" align="center" width="80" label="序号">
                    </el-table-column>
                    <el-table-column label="属性值">
                        <!-- row到底是谁?who are you? -->
                        <template #="{ row, $index }">
                            <el-input :ref="(vc) => (inputArr[$index] = vc)" v-if="row.flag" placeholder="请你输入属性值"
                                size="small" v-model="row.valueName" @blur="toLook(row, $index)"></el-input>
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #="{ row, $index }">
                            <el-button type="danger" size="small" :icon="Delete"
                                @click="attrParams.attrValueList.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="save" :disabled="attrParams.attrValueList.length > 0 ? false : true">
                    保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>
  
<script setup lang="ts">
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus,
    UploadFilled,
} from "@element-plus/icons-vue";
import useCategoryStore from "../../../stores/category";
//
//引入分类的仓库
import useCategryStore from "../../../stores/category";
let categoryStore = useCategoryStore();
//引入组合式APIwatch
import { watch, ref, reactive, nextTick } from "vue";
//引入请求函数
import { reqAttrList, reqAddOrUpdateAttr,reqDeleteAttr } from "../../../api/product/attr/attr";
import { ElMessage } from "element-plus";
import _ from "lodash";
//存储平台属性的数据
let attrList = ref([]);
//定义数组ref类型数据，将来存储el-input组件的实例
let inputArr = ref([]);
//控制div与input显示与隐藏

//将来添加或者修改属性需要参数
const attrParams = reactive({
    attrName: "", //新增|修改以后属性名字
    categoryId: "", //代表平台属性归属于手机这个三级分类下的
    categoryLevel: 3, //代表几级分类
    attrValueList: [
        //存储新增|修改属性值的数据
        // {
        //   valueName: "string", //属性值名字
        // },
    ],
});
//操作修改按钮
const updateAttr = (row) => {
    scene.value = 1;
    Object.assign(attrParams, _.cloneDeep(row));
}
//定义响应式变量控制场景切换---[2个]
let scene = ref<number>(0);
//监听三级分类的ID变化，如果发生变化需要发请求
watch(
    () => categoryStore.c3Id,
    () => {
        //判断:三级分类ID保证有数据
        if (categoryStore.c3Id == "") return;
        //获取平台属性方法
        getAttrList();
    }
);
//获取商品属性的方法
const getAttrList = async () => {
    let result = await reqAttrList(
        categoryStore.c1Id,
        categoryStore.c2Id,
        categoryStore.c3Id
    );

    //存储数据---平台属性
    attrList.value = result;
};

//添加属性按钮的回调
const addAttr = () => {
    //切换场景
    scene.value = 1;
    Object.assign(attrParams, {
        attrName: "",
        categoryId: categoryStore.c3Id, //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
        categoryLevel: 3,
        attrValueList: [],
    });
};
//取消按钮的点击事件[两个]
const cancel = () => {
    //切换场景为0
    scene.value = 0;
};

//添加属性值按钮的回调
const addAttrValue = () => {
    //向属性值数组添加元素
    attrParams.attrValueList.push({
        valueName: "",
        //给每一个属性值添加标记:用来切换编辑模式与查看模式
        flag: true,
    });
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus();
    });
};

//input失却焦点变为查看模式
const toLook = (row, $index) => {
    if (row.valueName.trim() == "") {
        ElMessage({
            type: "warning",
            message: "亲爱的属性值不能为空",
        });
        attrParams.attrValueList.splice($index, 1);
        return;
    }
    let repeat = attrParams.attrValueList.find((item) => {
        if (row != item) {
            return row.valueName === item.valueName
        }

    });
    if (repeat) {
        Elmessage({
            type: "warning",
            message: `${repeat.valueName}重复?`,
        });
        attrParams.attrValueList.splice($index, 1);
        return
    };
    row.flag = false;

};
//div点击切换为编辑模式
const toEdit = (row, $index) => {
    row.flag = true;
    //点击div切换显示el-input，需要聚焦
    nextTick(() => {
        inputArr.value[$index].focus();
    });
};
const save = async () => {
    //参数整理一下:属性值的数组flag属性不需要--->干掉
    attrParams.attrValueList.forEach((item) => {
        if (item.hasOwnProperty("flag")) {
            //删除某一个属性
            delete item.flag;
        }
    });
    try {
        //添加属性成功
        await reqAddOrUpdateAttr(attrParams);
        //切换场景
        scene.value = 0;
        //提示
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改成功" : "添加成功",
        });
        //获取全部最新的属性的数据
        getAttrList();
    } catch (error) {
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改失败" : "添加失败",
        });
    }
};
//删除已有数据
const removeAttr = async (row) => {
  try {
    //删除已有属性成功
    await reqDeleteAttr(row.id);
    //提示信息
    ElMessage({
      type: "success",
      message: `删除${row.attrName}成功`,
       duration:500,//约束提示信息的事件
    });
    //再次获取最新的属性的数据
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: `删除${row.attrName}失败`,
      duration:500
    });
  }
};
</script>
  
<style scoped>

</style>